import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/features/profile/viewmodels/edit_profile_viewmodel.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/utils/widget_extension.dart';

/// 编辑个人资料视图
/// 编辑个人资料功能页面
class EditProfileView extends StatefulWidget {
  const EditProfileView({super.key});

  @override
  State<EditProfileView> createState() => _EditProfileViewState();
}

class _EditProfileViewState extends State<EditProfileView> {
  late TextEditingController _usernameController;
  late TextEditingController _signatureController;

  @override
  void initState() {
    super.initState();
    _usernameController = TextEditingController();
    _signatureController = TextEditingController();
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _signatureController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<EditProfileViewModel>.reactive(
      viewModelBuilder: () => EditProfileViewModel(getIt.get())..initialize(),
      onViewModelReady: (viewModel) {
        // 初始化输入框的值
        if (viewModel.currentUser != null) {
          _usernameController.text = viewModel.username;
          _signatureController.text = viewModel.signature;
        }
      },
      builder: (context, viewModel, child) {
        // 当用户信息加载完成后，更新输入框
        if (viewModel.currentUser != null && _usernameController.text.isEmpty) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            _usernameController.text = viewModel.username;
            _signatureController.text = viewModel.signature;
          });
        }

        return Scaffold(
          body: Container(
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [Color(0xFFFFEBE6), Color(0xFFFFA680)],
              ),
            ),
            child: SafeArea(
              child:
                  viewModel.isBusy
                      ? const Center(child: CircularProgressIndicator())
                      : viewModel.currentUser == null
                      ? const Center(child: Text('Please login'))
                      : _buildContent(context, viewModel),
            ),
          ),
        );
      },
    );
  }

  /// 构建内容
  Widget _buildContent(BuildContext context, EditProfileViewModel viewModel) {
    final user = viewModel.currentUser!;
    final avatarSize = 90.w;
    final avatarRadius = avatarSize / 2;

    return [
      // 顶部标题栏
      _buildHeader(context),
      // 可滚动内容
      Expanded(
        child: SingleChildScrollView(
          child: [
                SizedBox(height: 20.h),
                // 用户信息编辑区域
                Stack(
                  clipBehavior: Clip.none,
                  children: [
                    // Container 主体
                    Container(
                      margin: EdgeInsets.only(top: avatarRadius),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16.r),
                        border: Border.all(
                          color: Colors.black.withOpacity(0.1),
                          width: 1.w,
                        ),
                      ),
                      padding: EdgeInsets.fromLTRB(
                        14.w,
                        avatarRadius + 20.h,
                        14.w,
                        20.w,
                      ),
                      child: [
                        // Nickname 输入框
                        Text(
                          'Nickname',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w600,
                            fontFamily:
                                GoogleFonts.alegreyaSans(
                                  fontWeight: FontWeight.w800,
                                ).fontFamily,
                            color: Colors.black,
                          ),
                        ),
                        SizedBox(height: 8.h),
                        _buildTextField(
                          controller: _usernameController,
                          hintText: user.username,
                          onChanged: viewModel.setUsername,
                        ),
                        SizedBox(height: 20.h),
                        // Personal signature 输入框
                        Text(
                          'Personal signature',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w600,
                            fontFamily:
                                GoogleFonts.alegreyaSans(
                                  fontWeight: FontWeight.w800,
                                ).fontFamily,
                            color: Colors.black,
                          ),
                        ),
                        SizedBox(height: 8.h),
                        _buildTextField(
                          controller: _signatureController,
                          hintText: user.signature ?? '',
                          onChanged: viewModel.setSignature,
                          maxLines: 3,
                        ),
                      ].verticalShot(
                        crossAxisAlignment: CrossAxisAlignment.start,
                      ),
                    ),
                    // 用户头像（一半在 container 外面，居中）
                    Positioned(
                      top: 0,
                      left: 0,
                      right: 0,
                      child: Center(
                        child: GestureDetector(
                          onTap: () => viewModel.selectAvatar(context),
                          child: Container(
                            width: avatarSize,
                            height: avatarSize,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border: Border.all(
                                color: Colors.white,
                                width: 2.w,
                              ),
                            ),
                            child: Stack(
                              children: [
                                CircleAvatar(
                                  radius: avatarRadius,
                                  backgroundColor: ColorConstants.primaryColor,
                                  backgroundImage: _getAvatarImage(
                                    viewModel.selectedAvatarPath ?? user.avatar,
                                  ),
                                  child:
                                      user.avatar == null &&
                                              viewModel.selectedAvatarPath ==
                                                  null
                                          ? Icon(
                                            Icons.person,
                                            size: 60.w,
                                            color: Colors.white,
                                          )
                                          : null,
                                ),
                                // 相机图标（居中）
                                Center(
                                  child: Container(
                                    width: 32.w,
                                    height: 32.w,
                                    decoration: BoxDecoration(
                                      color: Colors.black.withOpacity(0.3),
                                      shape: BoxShape.circle,
                                      border: Border.all(
                                        color: Colors.black.withOpacity(0.1),
                                        width: 2,
                                      ),
                                    ),
                                    padding: EdgeInsets.all(4.w),
                                    child: Image.asset(
                                      'assets/images/xiangji.png',
                                      width: 16.w,
                                      height: 16.w,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 100.h), // 底部留白
              ]
              .verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch)
              .frameHorizontal(14.w),
        ),
      ),
      // 底部保存按钮
      _buildSaveButton(context, viewModel),
    ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch);
  }

  /// 构建顶部标题栏
  Widget _buildHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Image.asset(
              'assets/images/back.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
          Expanded(
            child: Center(
              child: Text(
                'Profile',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w800,
                  fontFamily:
                      GoogleFonts.alegreyaSans(
                        fontWeight: FontWeight.w800,
                      ).fontFamily,
                  color: Colors.black,
                ),
              ),
            ),
          ),
          SizedBox(width: 24.w), // 平衡返回按钮
        ],
      ),
    );
  }

  /// 构建输入框
  Widget _buildTextField({
    required TextEditingController controller,
    required String hintText,
    required Function(String) onChanged,
    int maxLines = 1,
  }) {
    return TextField(
      controller: controller,
      onChanged: onChanged,
      maxLines: maxLines,
      style: TextStyle(
        fontSize: 16.sp,
        color: Colors.black87,
        fontFamily:
            GoogleFonts.alegreyaSans(fontWeight: FontWeight.w400).fontFamily,
      ),
      decoration: InputDecoration(
        hintText: hintText,
        hintStyle: TextStyle(
          color: Colors.grey[400],
          fontSize: 16.sp,
          fontFamily:
              GoogleFonts.alegreyaSans(fontWeight: FontWeight.w400).fontFamily,
        ),
        filled: true,
        fillColor: Colors.grey[100],
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
          borderSide: BorderSide.none,
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
          borderSide: BorderSide.none,
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8.r),
          borderSide: BorderSide(color: ColorConstants.accentColor, width: 2),
        ),
        contentPadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      ),
    );
  }

  /// 获取头像图片
  ImageProvider? _getAvatarImage(String? avatarPath) {
    if (avatarPath == null) {
      return null;
    }

    // 判断是本地文件路径还是asset路径
    if (avatarPath.startsWith('/') || avatarPath.startsWith('file://')) {
      // 本地文件路径
      return FileImage(File(avatarPath.replaceFirst('file://', '')));
    } else {
      // asset路径
      return AssetImage(avatarPath);
    }
  }

  /// 构建保存按钮
  Widget _buildSaveButton(
    BuildContext context,
    EditProfileViewModel viewModel,
  ) {
    return Container(
      padding: EdgeInsets.fromLTRB(14.w, 0, 14.w, 20.h),
      child: ElevatedButton(
        onPressed:
            viewModel.isBusy
                ? null
                : () async {
                  final success = await viewModel.saveUserInfo();
                  if (context.mounted) {
                    if (success) {
                      FlashNotifier.flashSuccess(
                        'Profile updated successfully',
                      );
                      Navigator.of(context).pop(true);
                    } else {
                      FlashNotifier.flashError('Failed to update profile');
                    }
                  }
                },
        style: ElevatedButton.styleFrom(
          padding: EdgeInsets.symmetric(vertical: 16.h),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.r),
          ),
          backgroundColor: ColorConstants.accentColor,
          foregroundColor: Colors.white,
          elevation: 0,
        ),
        child: Text(
          'Save',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.w600,
            fontFamily:
                GoogleFonts.alegreyaSans(
                  fontWeight: FontWeight.w600,
                ).fontFamily,
          ),
        ),
      ),
    );
  }
}
